<script setup>

import CardBox from "@/components/CardBox/index.vue";
import {Delete, Edit} from "@element-plus/icons-vue";
import {addLevelApi, deleteLevelApi, detailsLevelApi, getLevelListApi, updateLevelApi} from "@/api/school.js";
import {addNotice, updateNotice} from "@/api/system/notice.js";
import {formatDate} from "../../../../utils/index.js";
import {getToken} from "@/utils/auth.js";

const {proxy} = getCurrentInstance();

const showDia1 = ref(false)

const data = reactive({
  title: '新增',
  form: {},
  total: 0,
  tableData: [],
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  rules: {
    resName: [{required: true, message: "请输入学科竞赛", trigger: "blur"}],
    resLevel: [{required: true, message: "请输入赛事认定等级", trigger: "blur"}],
    resLevel2: [{required: true, message: "请输入获奖", trigger: "blur"}],
    hightLevel: [{required: true, message: "请选择高质量", trigger: "blur"}],
  },
  open:false
});
const upload = reactive({
  // 学生导入 教师导入
  type: 1,
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/school/level/importData"
});

const addForm = reactive({
  resName: '',
  resLevel: '',
  id: '',
})

const handleAdd = () => {
  showDia1.value = true
}

const closeDia1 = () => {
  showDia1.value = false
  Object.keys(addForm).forEach(key => {
    addForm[key] = ''
  })
}

const getDataList = async () => {
  const res = await getLevelListApi(data.queryParams)
  if (res.code == 200) {
    data.tableData = res.rows
    data.total = res.total
  }
}

const submitForm = () => {
  proxy.$refs["formRef"].validate(async valid => {
    if (valid) {
      let res;
      if (addForm.id != '') {
        res = await updateLevelApi(addForm)
      } else {
        res = await addLevelApi(addForm)
      }
      if (res.code == 200) {
        proxy.$modal.msgSuccess("操作成功")
      }
      closeDia1()
      await getDataList()
    }
  });
}

const handleDelete = (id) => {
  proxy.$modal.confirm('是否删除该数据？').then(async () => {
    const res = await deleteLevelApi({id})
    if (res.code == 200) {
      proxy.$modal.msgSuccess("删除成功")
    }
    await getDataList()
  })
}

const handleEdit = async (id) => {
  showDia1.value = true
  data.title = '编辑'
  addForm.id = id
  const res = await detailsLevelApi({id})
  addForm.resName = res.data.resName
  addForm.resLevel = res.data.resLevel
  addForm.hightLevel = res.data.hightLevel
}

const handleType2 = (item) => {
  proxy.$router.push({
    path: '/baseData/achievements2',
    query: {
      id: item.id
    }
  })
}

const handleExports = () => {
  proxy.download("school/level/exportTemplate1", {
  },`学科竞赛${new Date().getTime()}.xlsx`);
}

const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
const handleImport = () => {
  upload.open = true
}

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getDataList();
};

function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};

function importTemplate() {
  proxy.download("school/level/exportTemplate", {
  }, `学科竞赛级别导入模板${new Date().getTime()}.xlsx`);
};


onMounted(() => {
  getDataList()
})
</script>

<template>
  <div class="outBox">
    <CardBox title="学科竞赛">
      <template #btn-cont>
        <el-button type="primary" @click="handleAdd">新建</el-button>
        <el-button type="primary" :icon="exports" @click="handleExports">导出</el-button>
        <el-button type="primary" :icon="exports" @click="handleImport">导入</el-button>
      </template>
      <template #content>
        <el-table :data="data.tableData" style="width: 100%">
          <el-table-column label="序号" type="index" width="180" align="center"/>
          <el-table-column prop="resName" label="学科竞赛" align="center"/>
          <el-table-column prop="resLevel" label="赛事认定等级" align="center"/>
          <el-table-column prop="hightLevel" label="高质量赛事" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.hightLevel == 1" type="success">是</el-tag>
              <el-tag v-else type="danger">否</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" align="center">
            <template #default="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="resType" label="竞赛类型" align="center"/>

          <el-table-column label="操作" align="center" width="200">
            <template #default="scope">
              <div class="btns">
                <div class="btn">
                  <el-icon color="#152584" @click="handleEdit(scope.row.id)">
                    <Edit/>
                  </el-icon>
                </div>
                <div class="btn" @click="handleDelete(scope.row.id)">
                  <el-icon color="#152584">
                    <Delete/>
                  </el-icon>
                </div>
                <el-link @click="handleType2(scope.row)">子类型</el-link>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="pageBox">
          <pagination
              v-show="data.total > 0"
              :total="data.total"
              v-model:page="data.queryParams.pageNum"
              v-model:limit="data.queryParams.pageSize"
              @pagination="getDataList"
          />
        </div>
      </template>
    </CardBox>


    <el-dialog
        v-model="showDia1"
        :title="data.title"
        width="500"
        align-center
        :before-close="closeDia1"
    >
      <el-form :model="addForm" ref="formRef" label-width="auto" inline="true" :rules="data.rules">
        <el-form-item label="学科竞赛：" prop="resName">
          <el-input v-model="addForm.resName"/>
        </el-form-item>
        <el-form-item label="赛事认定等级：" prop="resLevel">
          <el-input v-model="addForm.resLevel"/>
        </el-form-item>
        <el-form-item label="高质量赛事：" prop="hightLevel">
          <el-radio-group v-model="addForm.hightLevel">
            <el-radio label="是" :value="1"></el-radio>
            <el-radio label="否" :value="0"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="竞赛类型：" prop="resType">
          <el-input v-model="addForm.resType"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDia1 = false">取消</el-button>
          <el-button type="primary" @click="submitForm">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>


    <el-dialog title="导入" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                 :action="upload.url + '?type=' + upload.type"
                 :disabled="upload.isUploading"
                 :on-progress="handleFileUploadProgress"
                 :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
            <br>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<style scoped lang="scss">
.content {
  padding: 20px;
}

.btns {
  display: grid;
  justify-content: center;
  grid-template-columns: 1fr 1fr 1fr;
}

.btn {
  cursor: pointer;
}
</style>
